package com.lingshi.shopping_goods_service.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.shopping.entity.Specification;
import com.lingshi.shopping.entity.SpecificationOption;
import com.lingshi.shopping.entity.SpecificationOptions;
import com.lingshi.shopping.service.SpecificationService;
import com.lingshi.shopping_goods_service.mapper.SpecificationMapper;
import com.lingshi.shopping_goods_service.mapper.SpecificationOptionMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@DubboService
public class SpecificationServiceImpl implements SpecificationService {

    @Autowired
    private SpecificationMapper specificationMapper;

    @Autowired
    private SpecificationOptionMapper specificationOptionMapper;

    @Override
    public void add(Specification specification) {
        specificationMapper.insert(specification);
    }

    @Override
    public void update(Specification specification) {
        specificationMapper.updateById(specification);
    }

    @Override
    public void delete(Long[] ids) {
        /**
         *  判断商品规格是否有商品关联
         *  1，有：抛出逻辑异常，不能删除
         *  2，没有：删除
         */
        specificationMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public Specification findById(Long id) {
        return specificationMapper.selectByPrimaryKey(id);
    }

    @Override
    public Page<Specification> search(int page, int size) {
        Page<Specification> specificationPage = new Page<>(page, size);
        specificationMapper.selectPage(specificationPage, null);
        return specificationPage;
    }

    @Override
    public List<Specification> findByProductTypeId(Long productTypeId) {

        List<Specification> specifications = specificationMapper.selectProductTypeId(productTypeId);


        return specifications;
    }

    @Override
    @Transactional
    public void addOption(SpecificationOptions specificationOptions) {

        String[] optionNames = specificationOptions.getOptionName();
        for (String optionName : optionNames) {
            SpecificationOption option = new SpecificationOption();
            option.setOptionName(optionName);
            option.setSpecId(specificationOptions.getSpecId());
            //新增规格项
            specificationOptionMapper.insert(option);
        }


    }

    @Override
    public void deleteOption(Long[] ids) {
        specificationOptionMapper.deleteBatchIds(Arrays.asList(ids));
    }
}
